//
//  ZBarScanVC.m
//  LazyCat
//
//  Created by linhui on 16/1/14.
//  Copyright (c) 2016年 zhanshu. All rights reserved.
//

#import "ZBarScanVC.h"
#import <AVFoundation/AVFoundation.h>
#import "QRCodeAreaView.h"
#import "QRCodeBacgrouView.h"
#import "UIViewExt.h"
#import "ScanPaySuccessVC.h"

#define SearchCOUNT 100
@interface ZBarScanVC ()<AVCaptureMetadataOutputObjectsDelegate>
{
    AVCaptureSession * session;//输入输出的中间桥梁
    QRCodeAreaView *_areaView;//扫描区域视图
    NSMutableArray *_TTTTTT;
    NSTimer *timer;// 定时器
    NSTimer *_timerForPaySearch;//定时查询订单支付状态
    UIView *_payingView;//支付中提醒View
    NSString *_orderNum;//查询用的支付订单号
    NSString *_payTime;//支付的时间
    NSInteger _requestCount;//请求次数，查询接口默认请求10次。
}

@end

@implementation ZBarScanVC
-(void)initNav:(NSString*)title doBack:(BOOL)doBack {
    self.navBar.hidden=NO;
    self.titleLable.text=title;
    self.titleLable.textColor = [UIColor whiteColor];
    if (doBack) {
        self.backBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        self.backBtn.frame=CGRectMake(8, 20+(44-21)/2, 12, 21);
        [self.backBtn setNormalImageWith:@"lALOCzPrgiYW_22_38"];
        [self.backBtn addTarget:self action:@selector(clickBackButton) forControlEvents:UIControlEventTouchUpInside];
        [self.backBtn setHitTestEdgeInsets:UIEdgeInsetsMake(-10, -14, -14, -25)];
        [self.navBar addSubview:self.backBtn];
    }
}
-(void)backAction:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}
-(void)viewDidLoad{
    [super viewDidLoad];
    [self initNav:@"扫码收款" doBack:YES];
    
    self.navBar.backgroundColor = SetColor(0, 140, 206, 1);
    //扫描区域
    CGRect areaRect = CGRectMake((ScreenWidth - 218)/2, (ScreenHeight - 218)/2, 218, 218);
    
    //半透明背景
    QRCodeBacgrouView *bacgrouView = [[QRCodeBacgrouView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight - 64)];
    bacgrouView.scanFrame = areaRect;
    [self.view addSubview:bacgrouView];
    
    //设置扫描区域
    _areaView = [[QRCodeAreaView alloc]initWithFrame:areaRect];
    [self.view addSubview:_areaView];
    
    //提示文字
    UILabel *label = [UILabel new];
    NSString *noteStr = [NSString stringWithFormat:@"请扫用户支付宝（微信）支付码收款"];
    label.text = noteStr;
    label.textColor = [UIColor whiteColor];
    label.y = CGRectGetMaxY(_areaView.frame) + 20;
    [label sizeToFit];
    label.center = CGPointMake(_areaView.center.x, label.center.y);
    [self.view addSubview:label];
    
    UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(0, label.frame.origin.y + 30, ScreenWidth, 35)];
    NSString *noteStr1;
    if (_moneyStr == nil) {
        noteStr1 = [NSString stringWithFormat:@"¥ %@",@"0.00"];
    }else {
        noteStr1 = [NSString stringWithFormat:@"¥ %@",_moneyStr];
    }
    label1.font = [UIFont systemFontOfSize:25];
    label1.text = noteStr1;
    label1.textColor = [UIColor whiteColor];
    //label1.y = CGRectGetMaxY(_areaView.frame) + 50;
    //[label1 sizeToFit];
    //label1.center = CGPointMake(_areaView.center.x, label1.center.y);
    label1.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:label1];
    
    //返回键
//    UIButton *backbutton = [UIButton buttonWithType:UIButtonTypeCustom];
//    backbutton.frame = CGRectMake(12, 26, 42, 42);
//    [backbutton setBackgroundImage:[UIImage imageNamed:@"prev"] forState:UIControlStateNormal];
//    [backbutton addTarget:self action:@selector(clickBackButton) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:backbutton];
    
    /**
     *  初始化二维码扫描
     */
    
    //获取摄像设备
    AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //创建输入流
    AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    //创建输出流
    AVCaptureMetadataOutput * output = [[AVCaptureMetadataOutput alloc]init];
    
    //设置代理 在主线程里刷新
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    output.rectOfInterest = CGRectMake(_areaView.y/ScreenHeight, _areaView.x/ScreenWidth, _areaView.height/ScreenHeight, _areaView.width/ScreenWidth);
    
    //初始化链接对象
    session = [[AVCaptureSession alloc]init];
    //高质量采集率
//    [session setSessionPreset:AVCaptureSessionPresetHigh];
//    [session addInput:input];
//    [session addOutput:output];
//    //设置扫码支持的编码格式(如下设置条形码和二维码兼容)
//    output.metadataObjectTypes=@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
//    AVCaptureVideoPreviewLayer * layer = [AVCaptureVideoPreviewLayer layerWithSession:session];
//    layer.videoGravity=AVLayerVideoGravityResizeAspectFill;
//    layer.frame=self.view.layer.bounds;
    
//    [self.view.layer insertSublayer:layer atIndex:0];
    
    //开始捕获
    [session startRunning];
    _TTTTTT = [[NSMutableArray alloc]init];
    [self createPayingView];
}

#pragma 二维码扫描的回调
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    if (metadataObjects.count>0) {
        [session stopRunning];//停止扫描
        [_areaView stopAnimaion];//暂停动画
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex : 0 ];
//        [[MessShowView share] showWithMess:@"扫一扫进一步功能正在努力开发中"];
        [[MessShowView share] showWithMess:@"扫描成功"];
        //输出扫描字符串
        NSLog(@"%@",metadataObject.stringValue);
        
        //扫码成功后弹出交易中view，成功了直接跳转到支付成功界面
        [UIView animateWithDuration:0.5 animations:^{
            _payingView.center = self.view.center;
        } completion:^(BOOL finished) {
            [self time];
            /**
             *  支付收款
             */
            NSString *payType;//支付宝14，微信15
            if ([_PayType isEqualToString:@"1"]) {//支付宝支付
                payType = @"14";
                NSString *kUrl = [NSString stringWithFormat:scanForPayUrl,[AppData share].username,_moneyStr,metadataObject.stringValue,payType];
                [AFNetworkHandler GETWithAFNByURL:kUrl completion:^(id result) {
                    NSDictionary *dic = result;
                    NSString *r = dic[@"r"];
                    if ([r isEqualToString:@"T"]) {
                        //[[MessShowView share]showWithMess:dic[@"支付成功"]];
                        NSDictionary *isNeedQueryOrder = (NSDictionary *)[dic objectForKey:@"pay"];
                        _orderNum = [isNeedQueryOrder objectForKey:@"orderno"];
                        _payTime = [isNeedQueryOrder objectForKey:@"paytime"];
                        if ([isNeedQueryOrder[@"isneedqueryorder"] isEqualToString:@"1"]) {//是否需要查询客户支付状态(需要[表示在等待客户支付]=1；不需要[表示客户已经支付成功]=0)
                            /**
                             *  time;;;
                             */
                            _requestCount = SearchCOUNT;
                            _timerForPaySearch = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(TheStatusOfPayForMoneyWithOrder:) userInfo:@"" repeats:YES];
                            
                            
                            
                        }else if ([isNeedQueryOrder[@"isneedqueryorder"] isEqualToString:@"0"]){//支付成功,  //SSSSSS....
                            //成功后跳转到支付成功界面
                            [self paySuccess];
                        }
                        
                    }else if ([r isEqualToString:@"F"]){//支付失败
                        [self payFail];//支付失败
                    }
                }];
                
            }else if ([_PayType isEqualToString:@"2"]){//微信支付
                payType = @"15";
                NSString *kUrl = [NSString stringWithFormat:scanForPayUrl,[AppData share].username,_moneyStr,metadataObject.stringValue,payType];
                [AFNetworkHandler GETWithAFNByURL:kUrl completion:^(id result) {
                    NSDictionary *dic = result;
                    NSString *r = dic[@"r"];
                    if ([r isEqualToString:@"T"]) {
                        
                        //[[MessShowView share]showWithMess:dic[@"支付成功"]];
                        NSDictionary *isNeedQueryOrder = (NSDictionary *)[dic objectForKey:@"pay"];
                        _orderNum = [isNeedQueryOrder objectForKey:@"orderno"];
                        _payTime = [isNeedQueryOrder objectForKey:@"paytime"];
                        if ([isNeedQueryOrder[@"isneedqueryorder"] isEqualToString:@"1"]) {//是否需要查询客户支付状态(需要[表示在等待客户支付]=1；不需要[表示客户已经支付成功]=0)
                            
                            
                            /**
                             *  time;;;
                             */
                            _requestCount = SearchCOUNT;
                            _timerForPaySearch = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(TheStatusOfPayForMoneyWithOrder:) userInfo:@"" repeats:YES];
                        }else if ([isNeedQueryOrder[@"isneedqueryorder"] isEqualToString:@"0"]){//支付成功,  //SSSSSS....
                            //成功后跳转到支付成功界面
                            [self paySuccess];
                        }
                        
                    }else if ([r isEqualToString:@"F"]){//支付失败
                        [self payFail];//支付失败
                    }
                }];
            }

        }];
        
//        NSString *str = [NSString stringWithFormat:@"setBillId('%@')",metadataObject.stringValue];
//        #define scanForPayUrl @"/App/LCatManager/Call?action=CreateF2FPayeeOrder&username=%@&amount=%@&authcode=%@&paytype=%@&subject=testSubject&remark=testRemark"
            }
}
#pragma mark -- 创建扫码成功后的界面
- (void)createPayingView {
    _payingView = [[UIView alloc]initWithFrame:CGRectMake((ScreenWidth - 250)/2, ScreenHeight, 250, 230)];
    _payingView.backgroundColor = [UIColor whiteColor];
    UILabel *TitleLabel = [[UILabel alloc]initWithFrame:CGRectMake((_payingView.size.width - 100)/2, 40, 100, 40)];
    //标题label
    TitleLabel.text = @"订单处理中";
    TitleLabel.font = [UIFont systemFontOfSize:18];
    TitleLabel.textAlignment = NSTextAlignmentCenter;
    [_payingView addSubview:TitleLabel];
    
    UILabel *descLabel = [[UILabel alloc]initWithFrame:CGRectMake((_payingView.size.width - 130)/2, 75, 130, 40)];
    //状态提示label (tag = 110)
    descLabel.text = @"请等待正在支付中...";
    descLabel.font = [UIFont systemFontOfSize:13];
    descLabel.textColor = SetColor(153, 153, 153, 1);
    descLabel.tag = 110;
    descLabel.textAlignment = NSTextAlignmentCenter;
    [_payingView addSubview:descLabel];
    
    //关闭倒计时按钮
    UIView *offView = [[UIView alloc]initWithFrame:CGRectMake((_payingView.size.width - 125)/2, 130, 125, 44)];
    offView.tag = 16;
    offView.backgroundColor = SetColor(187, 187, 187, 1);
    [_payingView addSubview:offView];
    
    UILabel *offLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 10, 90, 30)];
    //提示label
    offLabel.text = @"关闭(300s)";
    offLabel.textAlignment = NSTextAlignmentCenter;
    offLabel.textColor = [UIColor whiteColor];
    offLabel.tag = 15;
    offLabel.font = [UIFont systemFontOfSize:15];
    [offView addSubview:offLabel];
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    closeBtn.backgroundColor = [UIColor clearColor];
    closeBtn.frame = CGRectMake(0, 0, 90, 30);
    closeBtn.enabled = NO;
    closeBtn.tag = 17;
    [closeBtn addTarget:self action:@selector(closePayingView) forControlEvents:UIControlEventTouchUpInside];
    [offView addSubview:closeBtn];
    
    [self.view addSubview:_payingView];
}
#pragma mark - - 倒计时TTTTTTTTTTTTTTTTTTTimer
- (void)time {
    NSInteger count = 1;
    for (NSInteger i = 0; i < count; i++) {
        NSDictionary *dic = @{@"indexPath":[NSString stringWithFormat:@"%ld",i],@"lastTime": @"300"};
        [_TTTTTT addObject:dic];
        //NSLog(@"%ld",i);
    }
    [self startTimer];
}
- (void)startTimer
{
    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(refreshLessTime) userInfo:@"" repeats:YES];
    
    //如果不添加下面这条语句，在UITableView拖动的时候，会阻塞定时器的调用
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:UITrackingRunLoopMode];
    
}
- (void)refreshLessTime
{
    UIView *view = (UIView *)[self.view viewWithTag:16];
    UILabel *label = (UILabel *)[self.view viewWithTag:15];
    NSUInteger time;
    for (int i = 0; i < _TTTTTT.count; i++) {
        time = [[[_TTTTTT objectAtIndex:i] objectForKey:@"lastTime"] integerValue];
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:[[[_TTTTTT objectAtIndex:i] objectForKey:@"indexPath"] integerValue] inSection:1];
        NSInteger oldTime;
        if (time == 0) {
            oldTime = 0;
            view.backgroundColor = SetColor(0, 140, 206, 1);
            label.text = @"关闭";
            UIButton *btn = (UIButton *)[self.view viewWithTag:17];//关闭按钮
            btn.enabled = YES;
        }else {
            oldTime = --time;
            NSDictionary *dic = @{@"indexPath": [NSString stringWithFormat:@"%ld",indexPath.row],@"lastTime": [NSString stringWithFormat:@"%ld",time]};
            [_TTTTTT replaceObjectAtIndex:i withObject:dic];
            
            label.text = [NSString stringWithFormat:@"关闭(%lds)",oldTime];
        }
    }
}
#pragma mark -- 关闭掉支付中view
- (void)closePayingView {
    [UIView animateWithDuration:0.5 animations:^{
        _payingView.frame = CGRectMake((ScreenWidth - 250)/2, ScreenHeight, 250, 230);
    } completion:^(BOOL finished) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
}
//点击返回按钮回调
-(void)clickBackButton{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}
#pragma mark -- 支付...
- (void)PayForMoneyWithOrder:(NSString *)order {
    
}
#pragma mark -- 查询支付状态...
- (void)TheStatusOfPayForMoneyWithOrder:(NSString *)order {
    /**
     *查询支付状态
     */
    if (_requestCount == 0) {//请求100次后失败....FFFFFF......
        [_timerForPaySearch invalidate];
        _timerForPaySearch = nil;
        [self payFail];//支付失败
    }else {
        _requestCount -= 1;
        NSString *theResultOfPay = [NSString stringWithFormat:scanForPayResultUrl,[AppData share].username,_orderNum];
        [AFNetworkHandler GETWithAFNByURL:theResultOfPay completion:^(id result) {
            NSDictionary *dic = result;
            
            if ([dic[@"r"] isEqualToString:@"T"]) {//查询成功   //SSSSSS.....
                //成功后跳转到支付成功界面
                //tradestatus 面对面支付订单交易状态，等待买家付款 = 0,交易支付成功 = 1,客户关闭交易 = 2
                NSString *payStatus = [dic[@"pay"] objectForKey:@"tradestatus"];
                NSLog(@"--=============%@",[dic objectForKey:@"m"]);
                NSLog(@"--====******%@",payStatus);
                if ([payStatus isEqualToString:@"0"]) {
                    
                }else if ([payStatus isEqualToString:@"1"]){//SSSSSS.....
                    [self paySuccess];
                }else if ([payStatus isEqualToString:@"2"]){//支付失败
                    [self payFail];//失败
                }

            }else {//查询失败
                
            }
        }];

    }
}
/**
 *  订单支付成功后
 */
- (void)paySuccess {
    if (timer) {
        [timer invalidate];
        timer = nil;
    }
    if (_timerForPaySearch) {
        [_timerForPaySearch invalidate];
        _timerForPaySearch = nil;
    }
    //成功后跳转到支付成功界面
    UILabel *statusLabel = (UILabel *)[self.view viewWithTag:110];
    statusLabel.text = @"订单支付成功";
    ScanPaySuccessVC *paySuccess = [[ScanPaySuccessVC alloc]init];
    paySuccess.notesStr = _notesStr;//备注
    paySuccess.payMoney = _moneyStr;//金额
    paySuccess.orderNum = _orderNum;//订单号
    paySuccess.payTime = _payTime;//支付时间
    //完成后还原提醒视图...
    _payingView.frame = CGRectMake((ScreenWidth - 250)/2, ScreenHeight, 250, 230);
    [self.navigationController pushViewController:paySuccess animated:YES];
    }
/**
 *  支付失败
 */
- (void)payFail {
    if (timer) {
        [timer invalidate];
        timer = nil;
    }
    if (_timerForPaySearch) {
        [_timerForPaySearch invalidate];
        _timerForPaySearch = nil;
    }
    UILabel *statuslLabel = (UILabel *)[self.view viewWithTag:110];
    statuslLabel.text = @"订单支付失败";
    UIView *view = (UIView *)[self.view viewWithTag:16];
    UILabel *label = (UILabel *)[self.view viewWithTag:15];
    view.backgroundColor = SetColor(0, 140, 206, 1);
    label.text = @"关闭";
    UIButton *btn = (UIButton *)[self.view viewWithTag:17];//关闭按钮
    btn.enabled = YES;
}
//-(void)viewWillAppear:(BOOL)animated{
//    [super viewWillAppear:animated];
//
//    self.navigationController.navigationBarHidden = YES;
//}

@end
